{% extends "base.html" %}

{% block title %}生成排班 - 算法生成照护计划{% endblock %}

{% block page_title %}生成智能排班{% endblock %}

{% block extra_css %}
<style>
    .form-section {
        margin-bottom: 20px;
        padding: 15px;
        border: 1px solid var(--tech-border);
        border-radius: 5px;
        background-color: rgba(1, 1, 43, 0.75);
    }
    
    .algorithm-options {
        margin-top: 10px;
        padding: 15px;
        border: 1px solid var(--tech-border);
        border-radius: 5px;
        background-color: rgba(1, 1, 43, 0.6);
    }
    
    #loading {
        display: none;
        text-align: center;
        margin: 20px 0;
        color: var(--tech-primary);
    }
    
    .response-container {
        padding: 15px;
        border: 1px solid var(--tech-border);
        border-radius: 5px;
        background-color: rgba(1, 1, 43, 0.8);
        box-shadow: 0 0 15px rgba(5, 238, 255, 0.3);
        margin-top: 20px;
        display: none;
    }
    
    .response-header {
        color: var(--tech-primary);
        margin-bottom: 10px;
        font-weight: 600;
        border-bottom: 1px solid var(--tech-border);
        padding-bottom: 10px;
    }
    
    #api-response {
        font-family: monospace;
        white-space: pre-wrap;
        color: #fff;
        padding: 10px;
        background-color: rgba(5, 238, 255, 0.1);
        border-radius: 5px;
        max-height: 400px;
        overflow-y: auto;
    }
    
    .api-panel {
        width: 100%;
        padding: 15px;
        background-color: rgba(1, 1, 43, 0.7);
        border: 1px solid var(--tech-border);
        border-radius: 5px;
        margin: 15px 0;
        color: #fff;
        font-family: monospace;
        white-space: pre-wrap;
        box-shadow: 0 0 10px rgba(5, 238, 255, 0.3);
    }

    .api-url {
        color: var(--tech-accent);
        background-color: rgba(5, 238, 255, 0.1);
        padding: 3px 6px;
        border-radius: 3px;
        font-weight: bold;
    }

    .api-method {
        color: #4CAF50;
        font-weight: bold;
    }
    
    .algo-option {
        margin-bottom: 15px;
        padding: 10px;
        border: 1px solid var(--tech-border);
        border-radius: 4px;
        background-color: rgba(1, 1, 43, 0.7);
    }
    
    .algo-header {
        font-weight: 600;
        color: var(--tech-primary);
        margin-bottom: 10px;
        display: flex;
        align-items: center;
    }
    
    .algo-icon {
        margin-right: 8px;
        font-size: 1.2rem;
    }
    
    .algo-desc {
        font-size: 0.9rem;
        color: #aaa;
        margin-bottom: 10px;
    }
    
    .tech-badge {
        background-color: rgba(5, 238, 255, 0.2);
        color: var(--tech-primary);
        border: 1px solid var(--tech-border);
        padding: 3px 8px;
        border-radius: 5px;
        font-size: 0.8rem;
        margin-right: 5px;
        display: inline-block;
    }
    
    .form-label {
        color: var(--tech-primary);
        font-weight: 500;
    }
    
    .form-control, .form-select {
        background-color: rgba(1, 1, 43, 0.7);
        border: 1px solid var(--tech-border);
        color: #fff;
    }
    
    .form-control:focus, .form-select:focus {
        background-color: rgba(1, 1, 43, 0.9);
        border-color: var(--tech-primary);
        color: #fff;
        box-shadow: 0 0 10px rgba(5, 238, 255, 0.5);
    }
</style>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <div class="tech-card">
            <div class="tech-card-header">
                <h5 class="card-title"><i class="fas fa-calendar-alt me-2"></i>智能照护排班算法</h5>
            </div>
            <div class="tech-card-body">
                <div class="row">
                    <div class="col-md-8">
                        <p>本接口使用高级智能算法为养老院生成最优的照护排班计划，支持以下功能：</p>
                        <ul>
                            <li>基于老人需求和护理员能力进行智能匹配</li>
                            <li>支持多种排班优化算法，包括遗传算法、模拟退火算法和混合优化算法</li>
                            <li>自动生成照护计划总表和详细照护时间线</li>
                            <li>根据老人活动需求和护理员专长进行最优资源分配</li>
                            <li>提供高度可配置的算法参数，满足不同场景需求</li>
                        </ul>
                    </div>
                    <div class="col-md-4">
                        <div class="api-panel">
API接口: <span class="api-url">/generate_and_save_schedule</span>
方法: <span class="api-method">POST</span>
格式: JSON</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row mt-4">
    <div class="col-md-12">
        <div class="tech-card">
            <div class="tech-card-header">
                <h5 class="card-title"><i class="fas fa-cogs me-2"></i>排班参数配置</h5>
            </div>
            <div class="tech-card-body">
                <form id="generateScheduleForm">
                    <div class="form-section">
                        <h6 class="text-light mb-4">基本参数</h6>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="start_date" class="form-label">排班日期</label>
                                <input type="date" class="form-control" id="start_date" name="start_date" value="{{ today_date }}">
                            </div>
                            <div class="col-md-6">
                                <label for="days_to_generate" class="form-label">排班天数</label>
                                <input type="number" class="form-control" id="days_to_generate" name="days_to_generate" value="1" min="1" max="30">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="elder_limit" class="form-label">老人数量限制</label>
                                <input type="number" class="form-control" id="elder_limit" name="elder_limit" value="5" min="1" max="100">
                            </div>
                            <div class="col-md-6">
                                <label for="caregiver_limit" class="form-label">护理员数量限制</label>
                                <input type="number" class="form-control" id="caregiver_limit" name="caregiver_limit" value="10" min="1" max="100">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-section">
                        <h6 class="text-light mb-4">算法选择</h6>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="algorithm_type" class="form-label">排班算法</label>
                                <select class="form-select" id="algorithm_type" name="algorithm_type">
                                    <option value="genetic">遗传算法</option>
                                    <option value="simulated_annealing">模拟退火算法</option>
                                    <option value="hybrid" selected>混合优化算法</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="objective_function" class="form-label">优化目标</label>
                                <select class="form-select" id="objective_function" name="objective_function">
                                    <option value="balanced" selected>平衡优化（推荐）</option>
                                    <option value="care_quality">照护质量优先</option>
                                    <option value="resource_efficiency">资源效率优先</option>
                                    <option value="caregiver_preference">护理员偏好优先</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="algorithm-options" id="algorithm-params">
                            <!-- 遗传算法参数 -->
                            <div class="algo-option" id="genetic-options">
                                <div class="algo-header">
                                    <i class="fas fa-dna algo-icon"></i>遗传算法参数
                                </div>
                                <div class="algo-desc">
                                    遗传算法通过模拟自然选择过程，生成多代解决方案，逐步寻找最优排班方案。
                                    <div class="mt-2">
                                        <span class="tech-badge">高适应性</span>
                                        <span class="tech-badge">全局搜索</span>
                                        <span class="tech-badge">多样性保持</span>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <label for="population_size" class="form-label">种群大小</label>
                                        <input type="number" class="form-control" id="population_size" name="population_size" value="100" min="20" max="500">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="generations" class="form-label">迭代代数</label>
                                        <input type="number" class="form-control" id="generations" name="generations" value="50" min="10" max="200">
                                    </div>
                                </div>
                                <div class="row mt-2">
                                    <div class="col-md-6">
                                        <label for="crossover_rate" class="form-label">交叉率</label>
                                        <input type="number" class="form-control" id="crossover_rate" name="crossover_rate" value="0.8" min="0.1" max="1.0" step="0.1">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="mutation_rate" class="form-label">变异率</label>
                                        <input type="number" class="form-control" id="mutation_rate" name="mutation_rate" value="0.2" min="0.01" max="0.5" step="0.01">
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 模拟退火算法参数 -->
                            <div class="algo-option" id="sa-options">
                                <div class="algo-header">
                                    <i class="fas fa-temperature-high algo-icon"></i>模拟退火算法参数
                                </div>
                                <div class="algo-desc">
                                    模拟退火算法通过模拟物理退火过程，在搜索空间中寻找全局最优解，避免陷入局部最优。
                                    <div class="mt-2">
                                        <span class="tech-badge">跳出局部最优</span>
                                        <span class="tech-badge">快速收敛</span>
                                        <span class="tech-badge">鲁棒性强</span>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <label for="initial_temperature" class="form-label">初始温度</label>
                                        <input type="number" class="form-control" id="initial_temperature" name="initial_temperature" value="100.0" min="10.0" max="1000.0" step="10.0">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="cooling_rate" class="form-label">冷却率</label>
                                        <input type="number" class="form-control" id="cooling_rate" name="cooling_rate" value="0.95" min="0.8" max="0.99" step="0.01">
                                    </div>
                                </div>
                                <div class="row mt-2">
                                    <div class="col-md-6">
                                        <label for="min_temperature" class="form-label">最低温度</label>
                                        <input type="number" class="form-control" id="min_temperature" name="min_temperature" value="0.1" min="0.01" max="10.0" step="0.1">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="iterations_per_temp" class="form-label">每温度迭代次数</label>
                                        <input type="number" class="form-control" id="iterations_per_temp" name="iterations_per_temp" value="20" min="5" max="100">
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 混合算法参数 -->
                            <div class="algo-option" id="hybrid-options">
                                <div class="algo-header">
                                    <i class="fas fa-code-branch algo-icon"></i>混合优化算法参数
                                </div>
                                <div class="algo-desc">
                                    混合优化算法结合了遗传算法和模拟退火算法的优点，先通过遗传算法找到潜在最优解，再通过模拟退火算法进行精细优化。
                                    <div class="mt-2">
                                        <span class="tech-badge">更高精度</span>
                                        <span class="tech-badge">更快收敛</span>
                                        <span class="tech-badge">强大适应性</span>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <label for="hybrid_generations" class="form-label">遗传算法迭代次数</label>
                                        <input type="number" class="form-control" id="hybrid_generations" name="hybrid_generations" value="30" min="10" max="100">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="hybrid_population" class="form-label">遗传算法种群大小</label>
                                        <input type="number" class="form-control" id="hybrid_population" name="hybrid_population" value="80" min="20" max="200">
                                    </div>
                                </div>
                                <div class="row mt-2">
                                    <div class="col-md-6">
                                        <label for="sa_iterations" class="form-label">退火算法迭代次数</label>
                                        <input type="number" class="form-control" id="sa_iterations" name="sa_iterations" value="50" min="10" max="200">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="hybrid_cooling_rate" class="form-label">退火冷却率</label>
                                        <input type="number" class="form-control" id="hybrid_cooling_rate" name="hybrid_cooling_rate" value="0.9" min="0.7" max="0.99" step="0.01">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-section">
                        <h6 class="text-light mb-4">约束条件</h6>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="respect_caregiver_preferences" name="respect_caregiver_preferences" checked>
                                    <label class="form-check-label" for="respect_caregiver_preferences">尊重护理员偏好</label>
                                </div>
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="balance_workload" name="balance_workload" checked>
                                    <label class="form-check-label" for="balance_workload">平衡工作负荷</label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="ensure_coverage" name="ensure_coverage" checked>
                                    <label class="form-check-label" for="ensure_coverage">确保全天候照护覆盖</label>
                                </div>
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="optimize_skill_match" name="optimize_skill_match" checked>
                                    <label class="form-check-label" for="optimize_skill_match">优化技能匹配度</label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="d-grid gap-2">
                        <button type="submit" class="btn tech-btn tech-btn-primary">
                            <i class="fas fa-calendar-plus me-2"></i>生成智能排班
                        </button>
                    </div>
                </form>

                <div id="loading" class="mt-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">正在生成排班...</span>
                    </div>
                    <p class="mt-2">正在生成排班，请稍候...</p>
                </div>

                <div class="response-container" id="responseContainer">
                    <div class="response-header">
                        <i class="fas fa-code me-2"></i>API 响应结果
                    </div>
                    <div id="api-response"></div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    $(document).ready(function() {
        // 初始化时显示默认选择的算法参数
        showAlgorithmOptions();
        
        // 算法选择变化时切换参数显示
        $('#algorithm_type').change(function() {
            showAlgorithmOptions();
        });
        
        // 显示选择的算法参数
        function showAlgorithmOptions() {
            const selectedAlgorithm = $('#algorithm_type').val();
            
            // 隐藏所有算法参数
            $('#genetic-options, #sa-options, #hybrid-options').hide();
            
            // 显示选中的算法参数
            if (selectedAlgorithm === 'genetic') {
                $('#genetic-options').show();
            } else if (selectedAlgorithm === 'simulated_annealing') {
                $('#sa-options').show();
            } else if (selectedAlgorithm === 'hybrid') {
                $('#hybrid-options').show();
            }
        }
        
        // 表单提交
        $('#generateScheduleForm').submit(function(e) {
            e.preventDefault();
            
            // 显示加载中
            $('#loading').show();
            $('#responseContainer').hide();
            
            // 获取表单数据
            const formData = {};
            $(this).serializeArray().forEach(function(item) {
                // 处理数字型数据
                if (['elder_limit', 'caregiver_limit', 'days_to_generate',
                     'population_size', 'generations', 'iterations_per_temp',
                     'hybrid_generations', 'hybrid_population', 'sa_iterations'].includes(item.name)) {
                    formData[item.name] = parseInt(item.value);
                } else if (['crossover_rate', 'mutation_rate', 'initial_temperature', 
                           'cooling_rate', 'min_temperature', 'hybrid_cooling_rate'].includes(item.name)) {
                    formData[item.name] = parseFloat(item.value);
                } else {
                    formData[item.name] = item.value;
                }
            });
            
            // 处理复选框
            formData.respect_caregiver_preferences = $('#respect_caregiver_preferences').is(':checked');
            formData.balance_workload = $('#balance_workload').is(':checked');
            formData.ensure_coverage = $('#ensure_coverage').is(':checked');
            formData.optimize_skill_match = $('#optimize_skill_match').is(':checked');
            
            // 根据选择的算法，只发送相关参数
            const selectedAlgorithm = formData.algorithm_type;
            if (selectedAlgorithm === 'genetic') {
                // 移除其他算法的参数
                delete formData.initial_temperature;
                delete formData.cooling_rate;
                delete formData.min_temperature;
                delete formData.iterations_per_temp;
                delete formData.hybrid_generations;
                delete formData.hybrid_population;
                delete formData.sa_iterations;
                delete formData.hybrid_cooling_rate;
            } else if (selectedAlgorithm === 'simulated_annealing') {
                // 移除其他算法的参数
                delete formData.population_size;
                delete formData.generations;
                delete formData.crossover_rate;
                delete formData.mutation_rate;
                delete formData.hybrid_generations;
                delete formData.hybrid_population;
                delete formData.sa_iterations;
                delete formData.hybrid_cooling_rate;
            }
            
            // 发送请求
            $.ajax({
                url: '/generate_and_save_schedule',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(response) {
                    $('#loading').hide();
                    $('#responseContainer').show();
                    
                    // 格式化JSON并显示
                    const formattedJson = JSON.stringify(response, null, 2);
                    $('#api-response').html(syntaxHighlight(formattedJson));
                    
                    // 显示成功消息
                    const successAlert = `
                        <div class="alert tech-alert tech-alert-success mt-3 mb-3">
                            <i class="fas fa-check-circle me-2"></i>排班生成成功！
                        </div>
                    `;
                    $('#responseContainer').prepend(successAlert);
                },
                error: function(xhr, status, error) {
                    $('#loading').hide();
                    $('#responseContainer').show();
                    
                    // 显示错误消息
                    const errorMsg = xhr.responseJSON ? xhr.responseJSON.error : '未知错误';
                    const errorAlert = `
                        <div class="alert tech-alert tech-alert-danger mt-3 mb-3">
                            <i class="fas fa-exclamation-triangle me-2"></i>排班生成失败: ${errorMsg}
                        </div>
                    `;
                    $('#responseContainer').prepend(errorAlert);
                    
                    // 显示错误详情
                    if (xhr.responseJSON) {
                        const formattedJson = JSON.stringify(xhr.responseJSON, null, 2);
                        $('#api-response').html(syntaxHighlight(formattedJson));
                    } else {
                        $('#api-response').text('无法获取详细错误信息');
                    }
                }
            });
        });
        
        // 语法高亮函数
        function syntaxHighlight(json) {
            if (typeof json != 'string') {
                json = JSON.stringify(json, undefined, 2);
            }
            json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
            return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
                let cls = 'text-white';
                if (/^"/.test(match)) {
                    if (/:$/.test(match)) {
                        cls = 'text-info';  // 键名
                    } else {
                        cls = 'text-warning'; // 字符串
                    }
                } else if (/true|false/.test(match)) {
                    cls = 'text-success';  // 布尔值
                } else if (/null/.test(match)) {
                    cls = 'text-danger';   // null
                } else if (/-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/.test(match)) {
                    cls = 'text-primary';  // 数字
                }
                return '<span class="' + cls + '">' + match + '</span>';
            });
        }
    });
</script>
{% endblock %}
